package com.zhangyx.comm;

import org.apache.log4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtils {

    private static final Logger log = Logger.getLogger(SerializeUtils.class);

    public static byte[] toBytes(Object obj) {
        byte[] ret = null;
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(bao);
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            ret = bao.toByteArray();
        } catch (Exception e1) {
            log.error("序列化为byte数组失败"+ e1.getMessage());
        }
        return ret;
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T getObjectFromBytes(Class<T> clazz,byte[] data){
        if (data == null) {
            return null;
        }
        T ret = null;
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        try {
            ObjectInputStream ois = new ObjectInputStream(bis);
            ret =(T) ois.readObject();
            ois.close();
        }catch(Exception e){
            log.error("反序列化失败:" + e.getMessage());
        }
        
        return ret;
    }

}
